from PySide2.QtWidgets import QMainWindow, QTableWidget, QApplication, QTableWidgetItem


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QTableWidget 铺满窗口")
        self.tableWidget = QTableWidget(self)
        self.setCentralWidget(self.tableWidget)
        self.createTable()

    def createTable(self):
        # 设置表头为5列
        self.tableWidget.setColumnCount(5)
        # 设置水平表头伸展
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        # 设置垂直表头伸展
        self.tableWidget.verticalHeader().setStretchLastSection(True)
        # 设置size policy以使QTableWidget铺满窗口
        sizePolicy = self.tableWidget.sizePolicy()
        sizePolicy.setHorizontalPolicy(sizePolicy.Expanding)
        sizePolicy.setVerticalPolicy(sizePolicy.Expanding)
        self.tableWidget.setSizePolicy(sizePolicy)

        # 填充表格以便可见
        for row in range(5):
            for column in range(5):
                self.tableWidget.setItem(row, column, QTableWidgetItem(f"Cell {row + 1}, {column + 1}"))


app = QApplication([])
window = MainWindow()

window.show()
app.exec_()












































































































































































